package com.situ.stmall.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.situ.stmall.entity.Goods;
import com.situ.stmall.entity.Shopcart;
import com.situ.stmall.mapper.GoodsMapper;
import com.situ.stmall.mapper.ShopcartMapper;
import com.situ.stmall.service.ShopcartService;

@Service
public class ShopcartServiceImpl implements ShopcartService{

	@Autowired
	private ShopcartMapper shopcartMapper;
	@Autowired
	private GoodsMapper goodsMapper;
	
	@Override
	public int add(Shopcart cart) {
		// 1. 查找有没有对应的购物车信息, 
		Shopcart selectCart = shopcartMapper.select(cart);
		
		if (selectCart != null) {
			// 在原来的基础上更新
			selectCart.setCount(selectCart.getCount()+1);
			// 更新到数据库
			return shopcartMapper.updateByPrimaryKey(selectCart);
			
		} else {
			// 直接插入
			return shopcartMapper.insert(cart);
		}
	}
	@Override
	@Transactional
	public List getByUserId(Integer userId) {
		// 1. 根据用户ID查询当前用户的所有购物车
		List<Shopcart> carts = shopcartMapper.selectByUserId(userId);
		
		// 2. 遍历 所有的购物车信息, 
		for (Shopcart cart : carts) {
			// 判断购物车信息是否正常
			if (cart.getCount() > cart.getGoods().getCount()) {
				// 修改这个购物车的数量
				cart.setCount(cart.getGoods().getCount());
				// 更新到数据库中
				shopcartMapper.updateByPrimaryKey(cart);
			}
		}
		 
		return carts;
	}
	
	@Override
	public Shopcart update(Shopcart cart) {
		// 验证一下商品的数量, 需要获取商品的信息
		Shopcart selectCart = shopcartMapper.selectByPrimaryKey(cart.getId());
		
		// 查询商品的信息
		Goods goods = goodsMapper.selectByPrimaryKey(selectCart.getGoodsId());
		
		if (goods.getCount() < cart.getCount()) {
			selectCart.setCount(goods.getCount());
			shopcartMapper.updateByPrimaryKey(selectCart);
		} else {
			shopcartMapper.updateByPrimaryKey(cart);
		}
		
		return shopcartMapper.selectByPrimaryKey(cart.getId());
	}
	@Override
	public List getByIds(Integer userId, Integer[] cartIds) throws Exception {
		List<Shopcart> carts = new ArrayList<>();
		
		// 2. 查询购物车的信息
		for (int i=0; i<cartIds.length; i++) {
			Shopcart cart = shopcartMapper.selectByPrimaryKey(cartIds[i]);
			carts.add(cart);
			
			// 2.1 验证cart是否存
			if (cart == null) {
				throw new Exception("购物车信息查询失败!!! 订单生成失败");
			}
			// 2.2 验证cart是不是你的
			if (userId != cart.getUserId()) {
				throw new Exception("购物车用户信息出错!!! 订单生成失败");
			}
			// 3.3验证商品库存是否够用
			if (cart.getCount() > cart.getGoods().getCount()) {
				throw new Exception("购买的商品库存不足!!! 订单生成失败");
			}
			// 3.4购物车的购买数量不能为0
			if (cart.getCount() <= 0) {
				throw new Exception("购买的商品数量不能为0!!!订单生成失败");
			}
		}
		
		return carts;
	}

}





